<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Ajax search results script
 *
 * This file is called by the YUI ajax script to populate the dropdown list
 * of matching users to the search query.
 * Seperate group functionality:
 * Course students can only view those in their current group && teachers
 * Teachers and > can view any user in any group
 *
 * @package   block_email_list
 * @copyright 2006 Michael Avelar
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once('../../../../config.php');
require_once('../lib.php');
require_once('../list.class.php');

global $USER; // or pass $userid as hidden param

$courseid = optional_param('course', SITEID, PARAM_INT);                 // Course ID
$query    = optional_param('query', '', PARAM_ALPHANUM);

if (! $course = $DB->get_record('course', array('id' => $courseid))) {
    print_error('invalidcourseid', 'block_email_list');
}

if ($course->id == SITEID) {
    $context = context_system::instance(); // SYSTEM context
} else {
    $context = context_course::instance($course->id); // Course context
}

$canseefullname = has_capability('moodle/site:viewfullnames', $context);

require_login($course->id, false); // No autologin guest

// Mailing lists support - require total count for JSON string
$ulcount = 0;
$like = $DB->sql_like('listname', '?');
$userlists = $DB->get_records_select('block_email_list_lists', "owner = ? AND $like",
                                     array($USER->id, $query .'%'));

if (($course->id != SITEID) && $userlists) {
    // must count only lists with members - not empty lists.
    foreach ($userlists as $ulist) {

        if ($DB->get_records('block_email_list_members', array('listid' => $ulist->id))) {
            $ulcount++;
        }
    }
}

// Get all records (up to 5) that even remotely match the search query.
$json_str = '';

if (($course->id != SITEID) && ($results = email_search_course_users($course, $query))) {
    $count = count($results);

    // Create the JSON string
    $json_str = '{ "ResultSet":
                    { "totalResultsAvailable":"5",
                      "totalResultsReturned":'.($count + $ulcount).',
                      "firstResultPosition":1,
                      "Result": [';

    if ($count > 0) {

        if (is_array($results)) {

            foreach ($results as $result) {
                $json_str .= ' {"Username": "'.email_fullname($result, $canseefullname).'",
                                "Userid":'.$result->id.'
                               }';
                $count--;

                if ($count != 0) {
                    $json_str .= ',';
                }
            }
        } else {
            $json_str .= '{"Username" : "'.$results->firstname.' '.$results->lastname.'",
                            "Userid" : '.$results->id.'
                          }';
        }
    }
}

// Add mailing-list support
if (($course->id != SITEID) && !empty($userlists) && $ulcount > 0) {

    if (empty($json_str)) {
        // Create the JSON string
        $json_str = '{ "ResultSet":
                        { "totalResultsAvailable":"5",
                          "totalResultsReturned":'.$ulcount.',
                          "firstResultPosition":1,
                          "Result": [';
    } else {
        $json_str .= ',';
    }
    $listobj = new maillist();

    foreach ($userlists as $ulist) {
        $listobj->id       = $ulist->id;
        $listobj->listname = $ulist->listname;
        $listobj->owner    = $ulist->owner;
        $listmembers = $listobj->get_members();
        $ulcount--;

        if (!empty($listmembers) && count($listmembers) > 0) {
            $userids = '';

            foreach ($listmembers as $elem) {

                if (!empty($userids)) {
                    $userids .= ',';
                }
                $userids .= $elem->userid;
            }
            $json_str .= ' {"Username": "'.$listobj->listname.'",
                            "Userid": "'.$userids.'"
                         }';

            if ($ulcount != 0) {
                $json_str .= ',';
            }
        }
    }
}

if (!empty($json_str)) {
    $json_str = rtrim($json_str, ',');
    $json_str .= '  ]
                  }
              }';
}

error_log("JSON_str: ". $json_str);
echo $json_str;